import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedPacketHandler {

    // 红包对象
    private RedPacket redPacket;

    // 创建一个集合用来保存拆分出来的小红包
    private List<Double> moenyList = new ArrayList<>();

    private List<User> userList;

    public RedPacketHandler(RedPacket redPacket, List<User> userList) {
        this.redPacket = redPacket;
        this.userList = userList;
    }

    // 四舍五入 小数点后保留两位
    public double round(double money) {
        return Math.round(money * 100.0) / 100.0;
    }

    // 在这个案例中该方法是最核心的东西
    // 这个方法干的事情是把一个大红包拆分成多个小红包
    public void spiltRedPacket() {

        double totalMoney = redPacket.getTotalMoney();
        int count = redPacket.getCount();

        // 创建一个随机数的类
        Random random = new Random();
        for (int i = 0; i < redPacket.getCount() - 1; i++) {
            // 计算每个小红包的金额
            double result = random.nextDouble() * (totalMoney / count) * 2;
            totalMoney -= result; // 每次拆分出一个红包都要从总金额中减少
            count--;
            moenyList.add(round(result)); // 把每次拆分的红包保存起来
        }
        moenyList.add(round(totalMoney)); // 最后一份红包保存起来
    }

    public void grabRedPacket() {
        for (int i = 0; i < userList.size(); i++) {
            userList.get(i).addMoney(moenyList.get(i));
        }
    }

    public void printUsers() {
        double total = 0;
        for (User user : userList) {
            System.out.println(user);
            total+=user.getBalance();
        }
        System.out.println("total:"+total);
    }
}
